package com.youlei.newgraduateproject.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.youlei.newgraduateproject.entity.CommonResult;
import com.youlei.newgraduateproject.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;

import static com.youlei.newgraduateproject.common.Const.CAPTCHA_KEY;

/**
 * @author youlei
 * @version 1.0
 * @Date 2021-05-09-0:21
 * 通过控制器生成图片验证码
 */
@Slf4j
@RestController
public class AuthController extends BaseController{
    @Autowired
    private Producer producer;

    /**
     * 生成图片验证码
     */
    @GetMapping("/captcha")
    public CommonResult<Map> captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //生成key code 和图片
        String code = producer.createText();
        String key = UUID.randomUUID().toString();
        BufferedImage image = producer.createImage(code);

        //传输图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        //对图片进行BASE64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/png;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        // 存储到redis中
        redisUtil.hset(CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);
        return new CommonResult(200,"返回验证码图片",
                MapUtil.builder().put("token", key).put("base64Img", base64Img).build());
    }


    @GetMapping("/sys/userInfo")
    public CommonResult userInfo(Principal principal) {

        SysUser sysUser = sysUserService.getByUserName(principal.getName());

        return new  CommonResult(
                200,
                "获取用户信息",
                MapUtil.builder()
                .put("id", sysUser.getId())
                .put("username", sysUser.getUsername())
                .put("avatar", sysUser.getAvatar())
                .put("created", sysUser.getCreated())
                .map()
        );
    }

}